// 销售数据页面混入
import {
	getMockSalesOverview,
	getMockSalesTrend,
	getMockAreaList,
	getMockBrandList,
	getMockBusinessTypes,
	getMockSalesDetailList
} from '@/pagesData/api/salesData'

export default {
	data() {
		return {
			// 页面状态
			loading: false,
			refreshing: false,
			
			// 选择器状态
			showAreaPicker: false,
			showBrandPicker: false,
			showTypePicker: false,
			showTimePicker: false,
			
			// 当前选择
			selectedArea: '朝阳区域',
			selectedBrand: '',
			selectedType: '',
			selectedTime: '',
			activeTimeTab: 0,
			
			// 时间选项
			timeTabs: ['昨天', '本周', '本月', '上月'],
			
			// 数据列表
			areaList: [],
			brandList: [],
			typeList: [],
			
			// 销售数据
			salesOverview: {
				totalAmount: 0,
				totalAmountTrend: 0,
				productSales: 0,
				productSalesTrend: 0,
				newStores: 0,
				newStoresTrend: 0,
				monthlyPickup: 0,
				monthlyPickupTrend: 0,
				totalStores: 0,
				totalStoresTrend: 0
			},
			
			// 图表数据
			chartData: [],
			chartLabels: [],
			
			// 详情列表
			dataList: []
		}
	},
	
	computed: {
		// 格式化金额
		formattedTotalAmount() {
			return this.formatNumber(this.salesOverview.totalAmount, 2)
		},
		
		formattedProductSales() {
			return this.formatNumber(this.salesOverview.productSales, 2)
		},
		
		// 趋势颜色
		totalAmountTrendColor() {
			return this.salesOverview.totalAmountTrend >= 0 ? '#4CAF50' : '#f44336'
		},
		
		productSalesTrendColor() {
			return this.salesOverview.productSalesTrend >= 0 ? '#4CAF50' : '#f44336'
		}
	},
	
	onLoad() {
		this.initPage()
	},
	
	onPullDownRefresh() {
		this.refreshData()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			this.loading = true
			try {
				await Promise.all([
					this.loadAreaList(),
					this.loadBrandList(),
					this.loadTypeList(),
					this.loadSalesData()
				])
			} catch (error) {
				console.error('初始化页面失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 刷新数据
		async refreshData() {
			this.refreshing = true
			try {
				await this.loadSalesData()
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('刷新数据失败:', error)
				this.showError('刷新失败')
			} finally {
				this.refreshing = false
				uni.stopPullDownRefresh()
			}
		},
		
		// 加载区域列表
		async loadAreaList() {
			try {
				const res = await getMockAreaList()
				if (res.code === 200) {
					this.areaList = res.data.map(item => item.name)
				}
			} catch (error) {
				console.error('加载区域列表失败:', error)
			}
		},
		
		// 加载品牌列表
		async loadBrandList() {
			try {
				const res = await getMockBrandList()
				if (res.code === 200) {
					this.brandList = res.data.map(item => item.name)
				}
			} catch (error) {
				console.error('加载品牌列表失败:', error)
			}
		},
		
		// 加载业务类型列表
		async loadTypeList() {
			try {
				const res = await getMockBusinessTypes()
				if (res.code === 200) {
					this.typeList = res.data.map(item => item.name)
				}
			} catch (error) {
				console.error('加载业务类型列表失败:', error)
			}
		},
		
		// 加载销售数据
		async loadSalesData() {
			try {
				const params = this.getQueryParams()
				
				// 并行加载数据
				const [overviewRes, trendRes, detailRes] = await Promise.all([
					getMockSalesOverview(params),
					getMockSalesTrend(params),
					getMockSalesDetailList(params)
				])
				
				// 处理概览数据
				if (overviewRes.code === 200) {
					this.salesOverview = overviewRes.data
				}
				
				// 处理趋势数据
				if (trendRes.code === 200) {
					this.chartData = trendRes.data.data
					this.chartLabels = trendRes.data.labels
				}
				
				// 处理详情列表
				if (detailRes.code === 200) {
					this.dataList = detailRes.data
				}
				
			} catch (error) {
				console.error('加载销售数据失败:', error)
				throw error
			}
		},
		
		// 获取查询参数
		getQueryParams() {
			return {
				area: this.selectedArea,
				timeType: this.getTimeType(),
				brand: this.selectedBrand,
				businessType: this.selectedType,
				startDate: this.selectedTime,
				endDate: this.selectedTime
			}
		},
		
		// 获取时间类型
		getTimeType() {
			const timeTypes = ['yesterday', 'week', 'month', 'quarter']
			return timeTypes[this.activeTimeTab] || 'month'
		},
		
		// 切换时间标签
		async switchTimeTab(index) {
			if (this.activeTimeTab === index) return
			
			this.activeTimeTab = index
			this.loading = true
			try {
				await this.loadSalesData()
			} catch (error) {
				console.error('切换时间失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 选择区域
		async selectArea(value) {
			this.selectedArea = value[0]
			this.showAreaPicker = false
			
			this.loading = true
			try {
				await this.loadSalesData()
			} catch (error) {
				console.error('切换区域失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 选择品牌
		async selectBrand(value) {
			this.selectedBrand = value[0]
			this.showBrandPicker = false
			await this.loadSalesData()
		},
		
		// 选择业务类型
		async selectType(value) {
			this.selectedType = value[0]
			this.showTypePicker = false
			await this.loadSalesData()
		},
		
		// 选择时间
		async selectTime(value) {
			this.selectedTime = value
			this.showTimePicker = false
			await this.loadSalesData()
		},
		
		// 导出数据
		exportData() {
			uni.showLoading({
				title: '导出中...'
			})
			
			// 模拟导出过程
			setTimeout(() => {
				uni.hideLoading()
				uni.showToast({
					title: '导出成功',
					icon: 'success'
				})
			}, 2000)
		},
		
		// 分享数据
		shareData() {
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 0,
				href: 'https://example.com/sales-data',
				title: '省区销售数据',
				summary: `${this.selectedArea}销售数据报告`,
				imageUrl: '/static/images/share-logo.png',
				success: () => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					})
				},
				fail: (err) => {
					console.error('分享失败:', err)
					uni.showToast({
						title: '分享失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 打印数据
		printData() {
			uni.showToast({
				title: '打印功能开发中',
				icon: 'none'
			})
		},
		
		// 更多操作
		moreActions() {
			uni.showActionSheet({
				itemList: ['详细报表', '数据分析', '设置提醒', '历史记录'],
				success: (res) => {
					const actions = ['showDetailReport', 'showDataAnalysis', 'setReminder', 'showHistory']
					const action = actions[res.tapIndex]
					if (this[action]) {
						this[action]()
					}
				}
			})
		},
		
		// 显示详细报表
		showDetailReport() {
			uni.navigateTo({
				url: '/pages/sales-report/index'
			})
		},
		
		// 显示数据分析
		showDataAnalysis() {
			uni.navigateTo({
				url: '/pages/data-analysis/index'
			})
		},
		
		// 设置提醒
		setReminder() {
			uni.showToast({
				title: '提醒设置功能开发中',
				icon: 'none'
			})
		},
		
		// 显示历史记录
		showHistory() {
			uni.navigateTo({
				url: '/pages/sales-history/index'
			})
		},
		
		// 格式化数字
		formatNumber(num, decimals = 0) {
			if (num === null || num === undefined) return '0'
			
			const number = parseFloat(num)
			if (isNaN(number)) return '0'
			
			return number.toLocaleString('zh-CN', {
				minimumFractionDigits: decimals,
				maximumFractionDigits: decimals
			})
		},
		
		// 显示错误信息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			})
		}
	}
}
